/* Filename: ftype.c
 * Description: 获取文件类型
 * Last modified: humble 20200301 19:18
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

static void usage(void);

static int ftype(const char *pathname) { // 返还文件类型
    struct stat statres;
    if(stat(pathname, &statres) < 0){ perror("stat"); exit(1); }

    if(S_ISREG(statres.st_mode))      { return '-'; } // is it a regular file?
    else if(S_ISDIR(statres.st_mode)) { return 'd'; } // directory?
    else if(S_ISCHR(statres.st_mode)) { return 'c'; } // character device?
    else if(S_ISBLK(statres.st_mode)) { return 'b'; } // block device?
    else if(S_ISFIFO(statres.st_mode)){ return 'p'; } // FIFO (named pipe)?
    else if(S_ISLNK(statres.st_mode)) { return 'l'; } // symbolic link?  (Not in POSIX.1-1996.)
    else if(S_ISSOCK(statres.st_mode)){ return 's'; } // socket?  (Not in POSIX.1-1996.)
    else{ return '?'; }
}

int main(int argc, char **argv) {
    if(argc != 2){ fprintf(stderr, "argc !=2"); usage(); exit(1); }
    printf("%c\n", ftype(argv[1]));
    return 0;
}

static void usage(void) {
#define USAGE "Usage:\n\
  Helloworld\n"
    printf(USAGE);
}
